package com.google.project.client.Sharing;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.project.client.Admin.ADMEntrypoint;
import com.google.project.client.Director.DRTEntrypoint;
import com.google.project.client.HumanResources.HMEntrypoint;
import com.google.project.client.Operator.OPTEntrypoint;
import com.google.project.client.ProjectManager.PMEntrypoint;
import com.google.project.client.Service.LoginService;
import com.google.project.client.Service.LoginServiceAsync;
import com.google.project.client.Service.MessageService;
import com.google.project.client.Service.MessageServiceAsync;
import com.google.project.client.Service.UploadService;
import com.google.project.client.Service.UploadServiceAsync;
import com.google.project.client.Service.UsersService;
import com.google.project.client.Service.UsersServiceAsync;
import com.google.project.shared.MessageDTO;
import com.google.project.shared.UsersDTO;
import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.Hidden;

public class CreateMessage extends Composite {


	private static final Binder binder = GWT.create(Binder.class);
	@UiField
	Button btnSend;
	@UiField
	Button btnClear;
	@UiField
	TextBox txtSubject;
	@UiField
	ListBox cboReceiver;
	@UiField
	TextArea taContent;
	@UiField
	ListBox cbUserGroup;
	@UiField
	TextBox txtUserName;
	@UiField
	Button btnSearch;
	@UiField
	Button btnBack;
	@UiField FormPanel formUpload;
	@UiField FileUpload fileUpload;
	@UiField Hidden forId;
	@UiField Hidden type;
	@UiField Hidden documentName;

	interface Binder extends UiBinder<Widget, CreateMessage> {
	}

	private final LoginServiceAsync loginService = GWT
			.create(LoginService.class);
	private final UploadServiceAsync uploadService = GWT.create(UploadService.class);
	private final MessageServiceAsync messageService = GWT
			.create(MessageService.class);
	private final UsersServiceAsync userService = GWT
			.create(UsersService.class);

	List<UsersDTO> listUser = new ArrayList<UsersDTO>();
	UsersDTO currUser = new UsersDTO();
	MessageDTO currentMessage = new MessageDTO();

	public CreateMessage() {
		initWidget(binder.createAndBindUi(this));
		getInfoUserLogin();
		initCbo();
	}

	// init userGroup
	public void initCbo() {
		// TODO Auto-generated method stub
		cbUserGroup.addItem("---Tất cả---", "-1");
		cbUserGroup.addItem("Giám đốc", "1");
		cbUserGroup.addItem("Quản lý", "2");
		cbUserGroup.addItem("Chỉ huy công trường", "3");
		cbUserGroup.addItem("Quản lý nhân sự", "4");
		cbUserGroup.addItem("Nhân viên", "5");
		cbUserGroup.addItem("Admin", "6");
		cbUserGroup.setSelectedIndex(-1);
		cboReceiver.addItem("---Lựa chon---", "-1");
		// lay tat ca user co tai khoan -status=2-
		userService.getUserList(new AsyncCallback<List<UsersDTO>>() {

			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onSuccess(List<UsersDTO> result) {
				for (UsersDTO usersDTO : result) {
					if (usersDTO.getStatus().equalsIgnoreCase("2")) {
						listUser.add(usersDTO);
					}

				}

			}
		});
	}

	// get all User

	// get info user login from session
	public void getInfoUserLogin() {
		loginService.getCurrentUserDTO(new AsyncCallback<UsersDTO>() {

			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onSuccess(UsersDTO result) {
				currUser = result;
			}
		});
	}

	// getData from form
	public void getData() {

		if (txtSubject.getText() != null) {
			currentMessage.setSubject(txtSubject.getText());
		}
		if (taContent.getText() != null) {
			currentMessage.setContent(taContent.getText());
		}
		currentMessage.setTypeId(1);
		currentMessage.setSenderId(currUser.getUserId());
		currentMessage.setSenderName(currUser.getUserName());
		currentMessage.setReceiverId(cboReceiver.getValue(cboReceiver
				.getSelectedIndex()));

		String[] ReceiverName = cboReceiver.getItemText(
				cboReceiver.getSelectedIndex()).split(" ");
		currentMessage.setReceiverName(ReceiverName[0]);
		currentMessage.setCreatedOnDate(new Date().getTime());
		// message cha
		currentMessage.setParentId("0");
		// 1-nguoi nhan chua doc
		currentMessage.setStatus(1);
		// currentMessage.setProjectId(currUser.getCurrentProjID());
	}

	@UiHandler("btnSend")
	void onBtnSendClick(ClickEvent event) {
		getData();
		// if (currUser.getCurrentProjID() == null
		// || currUser.getCurrentProjID().equalsIgnoreCase("")) {
		// Window.alert("Bạn chưa tham gia dự án!");
		// } else {
		if (cboReceiver.getValue(cboReceiver.getSelectedIndex())
				.equalsIgnoreCase("-1")) {
			Window.alert("Bạn chưa chọn người để gửi!");
			return;
		}
		messageService.sendMessage(currentMessage,
				new AsyncCallback<MessageDTO>() {

					@Override
					public void onFailure(Throwable caught) {
						Window.alert("Có lỗi xảy ra!");

					}

					@Override
					public void onSuccess(MessageDTO result) {
						formUpload.setEncoding(FormPanel.ENCODING_MULTIPART);
						formUpload.setMethod(FormPanel.METHOD_POST);
						forId.setDefaultValue(result.getId());
						type.setDefaultValue("4");
						uploadService.getBlobStoreUrl(new AsyncCallback<String>() {
							
							@Override
							public void onSuccess(String result) {
								formUpload.setAction(result.toString());
								formUpload.submit();
								formUpload.reset();
							}
							
							@Override
							public void onFailure(Throwable caught) {
								caught.printStackTrace();
							}
						});
						
						Window.alert("Gửi thành công!");
						if (currUser.getUserGroup() == 1) {
							DRTEntrypoint.get().DRTMessList();
						} else if (currUser.getUserGroup() == 2) {
							PMEntrypoint.get().PMMessageList();
						} else if (currUser.getUserGroup() == 3) {
							OPTEntrypoint.get().OPTMessageList();
						} else if (currUser.getUserGroup() == 4) {
							HMEntrypoint.get().HMMessList();
						}else if (currUser.getUserGroup() == 6) {
							ADMEntrypoint.get().ADMMessList();
						}
					}
				});
	}

	// }

	@UiHandler("btnClear")
	void onBtnClearClick(ClickEvent event) {
		txtSubject.setText("");
		taContent.setText("");
	}

	@UiHandler("btnSearch")
	void onBtnSearchClick(ClickEvent event) {
		cboReceiver.clear();
		// cboReceiver.addItem("---Lựa chon---", "-1");
		Boolean condition = true;
		List<UsersDTO> temple = new ArrayList<UsersDTO>();
		String userName = txtUserName.getText().trim();
		for (UsersDTO user : listUser) {
			if (userName != null && !userName.equalsIgnoreCase("")) {
				condition = condition
						&& (user.getUserName().contains(userName));
			}
			if ((cbUserGroup.getValue(cbUserGroup.getSelectedIndex()) != null)
					&& (!cbUserGroup.getValue(cbUserGroup.getSelectedIndex())
							.equalsIgnoreCase("-1"))) {
				Long userGroup = Long.parseLong(cbUserGroup
						.getValue(cbUserGroup.getSelectedIndex()));
				condition = condition && (user.getUserGroup() == userGroup);
			}
			if (condition) {
				temple.add(user);
			}
			condition = true;
		}
		if (temple.size() > 0) {
			for (UsersDTO user : temple) {
				String displayName = user.getUserName() + " ("
						+ user.getFullName() + ")";
				cboReceiver.addItem(displayName, user.getUserId());
			}
		}
	}

	@UiHandler("btnBack")
	void onBtnBackClick(ClickEvent event) {
		if (currUser.getUserGroup() == 1) {
			DRTEntrypoint.get().DRTMessList();
		}
		else if (currUser.getUserGroup() == 2) {
			PMEntrypoint.get().PMMessageList();
		} else if (currUser.getUserGroup() == 3) {
			OPTEntrypoint.get().OPTMessageList();
		}
		else if (currUser.getUserGroup() == 4) {
			HMEntrypoint.get().HMMessList();
		}
		else if (currUser.getUserGroup() == 6) {
			ADMEntrypoint.get().ADMMessList();
		}
	}
}
